package com.bootdo.common.task;

import com.bootdo.common.huobi.api.ApiClient;
import com.bootdo.common.huobi.response.MatchresultsOrdersDetailResponse;
import com.bootdo.common.utils.CalculationUtil;
import com.bootdo.timing.domain.CombCountDO;
import com.bootdo.timing.domain.OrderDO;
import com.bootdo.timing.service.CombCountService;
import com.bootdo.timing.service.OrderService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;
@Component
public class HuoCheckJob implements Job {

    @Autowired
    private OrderService orderService ;

    @Autowired
    CombCountService combCountService ;

    private static String API_KEY ="de2162ba-931a9dda-88f3caa2-uymylwhfeg";

    private static  String API_SECRET ="edcc7848-06c8ea9a-3995ea0e-07db4";
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        ApiClient client = new ApiClient(API_KEY, API_SECRET);
        Map<String,Object> reqMap = new HashMap<String,Object>();
        reqMap.put("state" ,1); // state = 1
       List<OrderDO> orderlist  =  orderService.list(reqMap);
       if (orderlist !=null && orderlist.size() > 0  ){
           orderlist.forEach(orderDO -> {
               String tradeOrder = orderDO.getTradeOrder();
               List orderList = new ArrayList();
               orderList.add(tradeOrder);
               //------------------------------------------------------ ordersDetail 订单详情 -------------------------------------------------------
               //{"status":"ok","err-code":null,"err-msg":null,"data":[{"symbol":"eosusdt","order-id":63082247609,"filled-points":"0.0","fee-deduct-currency":"","source":"spot-api","filled-fees":"0.00048086642599278","created-at":1578288491266,"filled-amount":"0.240433212996389891","price":"2.77","match-id":102781661525,"role":"taker","trade-id":101737171106,"id":9013644625,"type":"buy-market"}]}
               MatchresultsOrdersDetailResponse mOrdersDetail=   client.matchresults("63082247609");
               Map<String,Object>  mOrdersDetailMap  = (Map<String, Object>) mOrdersDetail.getData();
               if (mOrdersDetail == null || !"ok".equals(mOrdersDetail.getStatus())) {
                   return ;
               }
               Map<String,Object> orderData   =(Map<String,Object>)mOrdersDetail.getData();

               if ("filled".equals(orderData.get("state"))){
                   if (!"ok".equals(mOrdersDetail.getStatus())){
                       return ;
                   }
                   String  source=  String.valueOf(mOrdersDetailMap.get("source"));
                   String  filled_fees=  String.valueOf(mOrdersDetailMap.get("filled-fees"));
                   String  filled_amount=  String.valueOf(mOrdersDetailMap.get("filled-amount"));
                   String  price=  String.valueOf(mOrdersDetailMap.get("price"));
                   String  trade_id=  String.valueOf(mOrdersDetailMap.get("trade-id"));
                   String  type=  String.valueOf(mOrdersDetailMap.get("type"));
                   String symbol = String.valueOf(mOrdersDetailMap.get("symbol"));
                  int result =  updateSuccessOrderState(source,filled_fees,filled_amount, tradeOrder,price,trade_id,type);
                  if (result > 0 ){
                      countCombCurrencyInfo(symbol,filled_amount,tradeOrder);
                  }
               }

           });
       }
    }

    private void countCombCurrencyInfo( String symbol, String filled_amount,String tradeOrder) {
        Map<String,Object> checkMap = new HashMap<>();
        checkMap.put("tradeOrder",tradeOrder);
       List<OrderDO> orderDOS =  orderService.list(checkMap);
       if (!orderDOS.isEmpty()){
          OrderDO orderDO = orderDOS.get(0);
          BigDecimal buyTotalAmount =  orderDOS.get(0).getBuyAmount(); // 购买所花费的金额
           CombCountDO combCountDO = new CombCountDO() ;
           combCountDO.setBuyTotalNum(new BigDecimal(filled_amount));
           combCountDO.setBuyTotalPrice(buyTotalAmount);
           combCountDO.setCurrencyType(symbol);
           combCountDO.setCombId(orderDO.getCombId());
           combCountDO.setUserId(orderDO.getUserId());
           combCountDO.setCountTime(new Date());
           combCountService.updateCombCountInfo(combCountDO);
       }

    }

    private int  updateSuccessOrderState(
            String source ,
            String filled_fees ,
            String filled_amount ,
            String tradeOrder,
            String price ,
            String trade_id,
            String type
    ) {

        OrderDO orderReq  = new OrderDO();

        orderReq.setState(0);//成功
        orderReq.setTradeOrder(tradeOrder);
        orderReq.setUpdateTime(new Date());
        orderReq.setBuyNum(new BigDecimal(filled_amount));
        orderReq.setBuyPrice(new BigDecimal(price));
        orderReq.setTrade_id(trade_id);
        orderReq.setFilled_fees(new BigDecimal(filled_fees));
        orderReq.setSource(source);
        orderReq.setType(type);
        String buyTotalPrice =  CalculationUtil.multiply(price,filled_amount);
        orderReq.setTradeTime(new Date());
        orderReq.setBuyAmount(new BigDecimal(buyTotalPrice));
        return orderService.updateByOrderId(orderReq);
    }
}
